package phoneregistration.controller;

import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import phoneregistration.controller.converter.UserConverter;
import phoneregistration.controller.model.UserModel;
import phoneregistration.domain.User;

import phoneregistration.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

    private final UserService service;
    private final UserConverter converter;

    @Autowired
    public UserController(UserService service, UserConverter converter) {
        this.service = service;
        this.converter = converter;
    }

    @RequestMapping(value="/{id}", method = RequestMethod.GET)
    public @ResponseBody UserModel findOne(@PathVariable("id") String id) {
        Assert.notNull(id);
        return converter.convertEntityToModel(service.findOne(convertId(id)));
    }
    
    private long convertId(String id) {
        return Long.parseLong(id);
    }
    
    @RequestMapping(value="/", method = RequestMethod.GET)
    public @ResponseBody Set<UserModel> findAll() {
        Set<UserModel> models = new HashSet<UserModel>();
        for (User entity : service.findAll()) {
            models.add(converter.convertEntityToModel(entity));
        }
        return models;
    }
    
    @RequestMapping(value="/", method = RequestMethod.POST)
    public @ResponseBody UserModel create(@RequestBody UserModel model) {
        Assert.notNull(model);
        return save(model);
    }
    
    @RequestMapping(value="/{id}", method = RequestMethod.PUT)
    public @ResponseBody UserModel update(@PathVariable("id") String id, @RequestBody UserModel model) {
        Assert.notNull(id);
        Assert.notNull(model);
        model.setId(id);
        return save(model);
    }
    
    public UserModel save(UserModel model) {
        return converter.convertEntityToModel(service.save(converter.convertModelToEntity(model)));
    }

    @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
    public @ResponseBody void delete(@PathVariable("id") String id) {
        Assert.notNull(id);
        service.delete(convertId(id));
    }    
}
